import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/internal/Observable';
import { AppSettings } from '../config/app-settings';
import * as _ from 'lodash';
@Injectable({
  providedIn: 'root'
})
export class CountryAutoUtilsService {
  dropDownOptions = {
    countryList: [],
    stateList: [],
    cityList: []
  }
  dropDownSelected = {
    countrySelected: '',
    stateSelected: '',
    citySelected: ''
  }

  constructor(private httpClient: HttpClient) { }

  getCountryList(): Observable<any> {
    let header = _.cloneDeep(AppSettings.httpServerHeader);
    return this.httpClient.get(`${AppSettings.server_base}/common/country`, header);

  }


  getStateList(country): Observable<any> {
    let header = _.cloneDeep(AppSettings.httpServerHeader);
    header.params = new HttpParams().set('country', country);
    return this.httpClient.get(`${AppSettings.server_base}/common/state`, header);
  }


  getCityList(country, state): Observable<any> {
    let header = _.cloneDeep(AppSettings.httpServerHeader);
    header.params = new HttpParams().set('country', country).set('state', state);
    return this.httpClient.get(`${AppSettings.server_base}/common/city`, header)
  }





  constructDropDownOptions(country?, state?, city?) {
    this.dropDownSelected.countrySelected = country;
    this.dropDownSelected.stateSelected = state;
    this.dropDownSelected.citySelected =city;
    this.refreshDropDownOptions();

  }

  refreshDropDownOptions() {
    //load countries options
    this.getCountryList().subscribe(
      data => {
        this.dropDownOptions.countryList = _.map(data, (item)=>{
          return item;
        });
      });
    //load states options
    if (this.dropDownSelected.countrySelected) {
      this.getStateList(this.dropDownSelected.countrySelected).subscribe(data => {
        this.dropDownOptions.stateList = _.map(data, (item)=>{
          return item;
        });
      });
    }
    //load cities options
    if (this.dropDownSelected.countrySelected && this.dropDownSelected.stateSelected) {
      this.getCityList(this.dropDownSelected.countrySelected, this.dropDownSelected.stateSelected).subscribe(data => {
        this.dropDownOptions.cityList = _.map(data, (item)=>{
          return item;
        });
      });
    }
  }

  getSelectedCountry(): string {
    return this.dropDownSelected.countrySelected;
  }

  getSelectedState(): string {
    return this.dropDownSelected.stateSelected;
  }

  getSelectedCity(): string {
    return this.dropDownSelected.citySelected;
  }


}
